package com.bamboo.tool.util;

import com.bamboo.tool.view.component.notificationGroup.ToolWindowNotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import org.jetbrains.annotations.NotNull;

/**
 * @author bamboo
 * Date 2022/10/14 16:27
 * Description
 */
public class TaskUtil {

    public static void run(Project myProject, String title, Runnable rebuildRunnable) {

        Task.Backgroundable task = new Task.Backgroundable(myProject, title) {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setText(title + " 开始");
                ApplicationManager.getApplication().runReadAction(() -> {
                    try {
                        rebuildRunnable.run();
                        progressIndicator.setText(title + " 结束");
                    } catch (Exception e) {
                        ToolWindowNotificationGroup.NOTIFICATION_GROUP.createNotification(title + "执行失败：" + e.getMessage(), MessageType.ERROR).notify(myProject);
                        throw e;
                    }
                });
            }
        };
        ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));

    }
}
